package com.crazy.bookstore.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.crazy.bookstore.common.ApiRestResponse;
import com.crazy.bookstore.entity.Book;
import com.crazy.bookstore.exception.ExceptionEnum;
import com.crazy.bookstore.exception.MyException;
import com.crazy.bookstore.service.BookService;
import com.crazy.bookstore.vo.BookForAdminVO;
import org.apache.ibatis.annotations.Param;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author: 卢辉宇
 * @date: 2023/1/1 11:34
 * @description:
 */
@RestController
@RequestMapping("/admin/book")
public class BookForAdminController {
    @Resource
    BookService bookService;

    /**
     * 分页查询书本信息
     * @param page 不传入默认第一页
     * @param row 默认页大小为10条
     * @return
     */
    @GetMapping("/list")
    public ApiRestResponse list(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10") Integer row){
        IPage<BookForAdminVO> bookList = bookService.selectBookList(page, row);
        return ApiRestResponse.seccess(bookList);
    }

    /**
     * 富文本编辑器上传文件
     * @param file img与前端定义的保持一致
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public Map upload(@RequestParam("img") MultipartFile file, HttpServletRequest request) throws IOException {
        //得到文件上传路径,加上新建的upload路径，就是图片要保存的地方
        String path = request.getServletContext().getResource("/").getPath()+"/upload/";
        //生成毫秒级时间用作文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = sdf.format(new Date());
        //获取源文件的扩展名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        System.out.println("地址："+path+fileName+suffix);
        //把上传的文件保存到指定地方
        file.transferTo(new File(path+fileName+suffix));

        //按照wangEditor要求的组织回显结构
        Map result=new LinkedHashMap();
        result.put("errno",0);
        result.put("data",new String[]{"/upload/"+fileName+suffix});

        return result;
    }

    /**
     * 新增图书
     * @param book
     * @return
     * @throws MyException
     */
    @PostMapping("/create")
    public ApiRestResponse createBook(Book book) throws MyException {
        //由于前端传来的book对象字段只有5个，所以要补充剩下的字段
        //使用jsoup解析传来的html片段
        Document doc = Jsoup.parse(book.getDescription());
        //得到img标签对象
        Elements elements = doc.select("img");
        if (elements.size()==0){
            /*没有得到img标签*/
            throw new MyException(ExceptionEnum.NOT_FIND_IMG);
        }

        //拿到第一个img标签的src属性的值
        String src = elements.first().attr("src");

        //设置封面、评分、评论人数
        book.setCover(src);
        book.setEvaluationScore(0f);
        book.setEvaluationQuantity(0);

        bookService.createBook(book);

        return ApiRestResponse.seccess(book);
    }

    /**
     * 更新图书
     * @param book
     * @return
     * @throws MyException
     */
    @PostMapping("/update")
    public ApiRestResponse updateBook(Book book) throws MyException {
        //使用jsoup解析传来的html片段
        Document doc = Jsoup.parse(book.getDescription());
        //得到img标签对象
        Elements elements = doc.select("img");
        if (elements.size()==0){
            /*没有得到img标签*/
            throw new MyException(ExceptionEnum.NOT_FIND_IMG);
        }

        //拿到第一个img标签的src属性的值
        String src = elements.first().attr("src");

        //从数据库中查找图书
        Book b = bookService.selectById(book.getBookId());

        //更改数据
        b.setCover(book.getCover());
        b.setBookName(book.getBookName());
        b.setAuthor(book.getAuthor());
        b.setCategoryId(book.getCategoryId());
        b.setDescription(book.getDescription());

        bookService.updateBook(book);

        return ApiRestResponse.seccess(b);
    }

    @PostMapping("/delete")
    public ApiRestResponse deleteBook(Integer bookId){
        bookService.deleteBook(bookId);
        return ApiRestResponse.seccess();
    }

}
